//
//  YAYIAppointDetailViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/26.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIAppointDetailViewController.h"
#import "YAYIPatienInfoController.h"

#import "YAYIAppointDetailCell.h"
#import "YAYIAppointDetailHeadCell.h"
#import "YAYIMyAppointItem.h"

@interface YAYIAppointDetailViewController ()

@property (nonatomic, weak) UILabel *statusLbl;
@property (nonatomic, weak) UILabel *messageLbl;

@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, strong) YAYIAppointDetailHeadItem *headItem;

@end

@implementation YAYIAppointDetailViewController


- (NSMutableArray *)items
{
    if (nil == _items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"预约详情";
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];
//    self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, -35, 0);
    self.tableView.separatorColor = YAYIColor(0xE5, 0xE5, 0xE5);
    
    self.tableView.sectionFooterHeight = 0;
    self.tableView.sectionHeaderHeight = 10;
    
    [self setupHeaderView];
    [self setupFooterView];
    [self getAppointDetail];
}


- (instancetype)initWithStyle:(UITableViewStyle)style
{
    return [super initWithStyle:UITableViewStyleGrouped];
}


- (void)setupHeaderView
{
    UILabel *headerLbl = [[UILabel alloc] init];
    headerLbl.backgroundColor = YAYIColor(242, 242, 242);
    headerLbl.textColor = YAYIColor(156, 156, 156);
    headerLbl.font = [UIFont systemFontOfSize:13];
    headerLbl.textAlignment = NSTextAlignmentCenter;
    headerLbl.text = @"订单状态：已就诊";
    
    headerLbl.height = 35;
    headerLbl.width = SCREEN_width;
    self.statusLbl = headerLbl;
    
    self.tableView.tableHeaderView = headerLbl;
}


- (void)setupFooterView
{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.mj_w = SCREEN_width;
    bgView.mj_h = 80;
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"留言";
    titleLbl.font = [UIFont systemFontOfSize:15];
    titleLbl.textColor = YAYIColor(146, 146, 146);
    [bgView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(@10);
    }];
    
    UILabel *detailLbl = [[UILabel alloc] init];
    detailLbl.font = [UIFont systemFontOfSize:15];
    detailLbl.numberOfLines = 0;
    detailLbl.text = @"医生你好，我的左上的智齿疼";
    [bgView addSubview:detailLbl];
    self.messageLbl = detailLbl;
    [detailLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLbl);
        make.top.equalTo(titleLbl.mas_bottom).offset(10);
    }];
    
    
    
    self.tableView.tableFooterView = bgView;
}


#pragma mark - 获取数据
- (void)getAppointDetail
{
    // 显示hud
    [SVProgressHUD show];
    
    NSArray *titleParamnameArray = @[@{@"title":@"就诊医院", @"paramname":@"hospitalname"},
                                     @{@"title":@"医生职称", @"paramname":@"title"},
                                     @{@"title":@"初/复诊", @"paramname":@"isfirst"},
                                     @{@"title":@"门诊时间", @"paramname":@"starttime"},
                                     @{@"title":@"预约时段", @"paramname":@"starttime"},
                                     ];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.appointID;
    [YAYINetWorking getWithURL:appointDetail_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSDictionary *data = dict[@"data"];
                // 状态
                self.statusLbl.text = [data[@"isorder"] integerValue] == 0 ? @"订单状态：未就诊" : @"订单状态：已就诊";
                NSInteger appointState = [data[@"d"] integerValue];
                NSInteger orderState = [data[@"isorder"] integerValue];
                if(1 == appointState){ // 已取消
                    
                    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"预约状态：已取消"];
                    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(5, 3)];
                    self.statusLbl.attributedText = attriStr;
                }else if(1 == orderState){ // 已就诊
                    
                    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"订单状态：已就诊"];
                    [attriStr addAttribute:NSForegroundColorAttributeName value:YAYIColor(230, 97, 45) range:NSMakeRange(5, 3)];
                    self.statusLbl.attributedText = attriStr;
                }else if(0 == orderState){ // 未就诊
                    
                    NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:@"订单状态：未就诊"];
                    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 3)];
                    self.statusLbl.attributedText = attriStr;
                }
                
                // 头像
                YAYIAppointDetailHeadItem *headItem = [[YAYIAppointDetailHeadItem alloc] init];
                headItem.patientName = data[@"patientName"];
                headItem.mobile = data[@"mobile"];
                headItem.avatar = data[@"avatar"];
                headItem.userid = [data[@"userid"] integerValue];
                self.headItem = headItem;
                
                // 留言
                self.messageLbl.text = data[@"msg"] && ![data[@"msg"] isKindOfClass:[NSNull class]] ? data[@"msg"] : @"";
                
                // 中间数据
                for (int i = 0; i < titleParamnameArray.count; i++) {
                    YAYIAppointDetailItem *item = [YAYIAppointDetailItem new];
                    item.title = titleParamnameArray[i][@"title"];
                    NSString *keyStr = titleParamnameArray[i][@"paramname"];
                    NSString *valueStr = data[keyStr];
                    
                    if (2 == i) {
                        item.detail = [valueStr integerValue] == 0 ? @"初诊" : @"复诊";
                    }else if (3 == i){
                        item.detail = [self dataStrWith:valueStr];
                    }else if (4 == i){
                        
                        item.detail = [self timeIntervalWith:valueStr timeLong:data[@"timelong"]];
                    }else{
                        item.detail = valueStr;
                    }
                    
                    [self.items addObject:item];
                }
                
                [self.tableView reloadData];
            }

        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
    
}


#pragma mark - 工具方法
/**
 *  时间转换成类似  2016-05-14 下午格式
 */
- (NSString *)dataStrWith:(NSString *)dataStamp
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dataStamp integerValue]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setAMSymbol:@"上午"];
    [formatter setPMSymbol:@"下午"];
    formatter.dateFormat = @"yyyy-MM-dd  a";
    
    NSString *dateStr = [formatter stringFromDate:date];
    
    YAYILog(@"data:%@ %@", dataStamp, dateStr);
    
    return dateStr;
}

/**
 *  时间戳+市场转换成 时段 如：03:30-04:20
 */
- (NSString *)timeIntervalWith:(NSString *)startTimeStamp timeLong:(NSString *)timeLong
{
    NSInteger startTime = [startTimeStamp integerValue];
    NSInteger endTime = startTime + [timeLong integerValue];
    
    NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:startTime];
    NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:endTime];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"hh:mm";
    
    NSString *startTimeStr = [formatter stringFromDate:startDate];
    NSString *endTimeStr = [formatter stringFromDate:endDate];
    
    YAYILog(@"时段：%@", [NSString stringWithFormat:@"%@-%@", startTimeStr, endTimeStr]);
    
    return [NSString stringWithFormat:@"%@-%@", startTimeStr, endTimeStr];
}


#pragma mark - 代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (0 == section) {
        return 1;
    }
    return self.items.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return 80;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0 == indexPath.section) {
        YAYIAppointDetailHeadCell *cell = [YAYIAppointDetailHeadCell cellWith:tableView];
        
        if (self.headItem) {
            cell.item = self.headItem;
        }
        return cell;
    }
    
    YAYIAppointDetailCell *cell = [YAYIAppointDetailCell cellWith:tableView];
    [cell setLayoutMargins:UIEdgeInsetsZero];
    cell.item = self.items[indexPath.row];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (0 == indexPath.row) {
        
        YAYIPatienInfoController *patientInfoVc = [[YAYIPatienInfoController alloc] init];
        patientInfoVc.isAccepted = YES;
        patientInfoVc.userid = [NSString stringWithFormat:@"%ld", self.headItem.userid];
        YAYILog(@"");
        [self.navigationController pushViewController:patientInfoVc animated:YES];
    }
}


@end
